package cn.simon.rabbitmq;

import cn.simon.pojo.SeckillMessage;
import cn.simon.pojo.SeckillOrder;
import cn.simon.pojo.User;
import cn.simon.service.IGoodsService;
import cn.simon.service.IOrderService;
import cn.simon.util.JsonUtil;
import cn.simon.vo.GoodsVo;
import cn.simon.vo.RespBean;
import cn.simon.vo.RespBeanEnum;
import com.rabbitmq.tools.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @功能描述： 消费者-接收消息
 * @Auther: simon-yi'an
 */
@Slf4j
@Service
public class MQseckillReceive {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;

    @RabbitListener(queues = "seckill_queue")
    public void seckill_queueReceive(String message){
        log.info("接收到的消息："+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();

        //在数据库中判读库存
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        if(goodsVo.getStockCount()  <= 0){
            return;
        }
        //判断是否重新抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("userId:" + user.getId() + ":" + goodsId);
        if(seckillOrder != null){
            return ;
        }

        //下单操作
        orderService.seckill(user,goodsVo);


    }
}
